package com.example.gulimall.cart.introceptor;

import com.alibaba.fastjson.JSONObject;
import com.example.common.constant.AuthServerConstant;
import com.example.common.constant.CartConstant;
import com.example.common.entity.member.MemberEntity;
import com.example.common.utils.GuLiMallThreadLocalPool;
import com.example.common.to.cart.UserInfoTo;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;
import java.util.UUID;

/**
 * <p>
 *      执行目标方法之前，判断用户是临时用户还是登录后的用户
 * </p>
 *
 * @author zyred
 * @since v 0.1
 **/
public class CartInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) {

        UserInfoTo to = new UserInfoTo();

        Object attribute = request.getSession()
                .getAttribute(AuthServerConstant.SESSION_LOGIN_KEY);
        String json = String.valueOf(attribute);
        MemberEntity memberEntity = JSONObject.parseObject(json, MemberEntity.class);
        if (Objects.nonNull(memberEntity)) {
            to.setUserId(memberEntity.getId());
        }
        Cookie[] cookies = request.getCookies();

        if (Objects.nonNull(cookies)) {
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                if (Objects.equals(CartConstant.TEMP_USER_COOKIE_KEY, name)) {
                    to.setUserKey(cookie.getValue());
                    to.setLogin(Objects.isNull(to.getUserId()));
                }
            }
            createUserKey(to);
        }
        GuLiMallThreadLocalPool.setUsers(to);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response,
                           Object handler,
                           ModelAndView modelAndView) {

        UserInfoTo users = GuLiMallThreadLocalPool.getRemove();

        if (users.isLogin()) {
            Cookie c = new Cookie(CartConstant.TEMP_USER_COOKIE_KEY, users.getUserKey());
            c.setMaxAge(CartConstant.TEMP_USER_COOKIE_MAX_AGE);
            c.setDomain(AuthServerConstant.GLOBAL_DOMAIN_NAME);
            response.addCookie(c);
        }

    }


    private void createUserKey (UserInfoTo info) {
        if (StringUtils.isBlank(info.getUserKey())) {
            info.setUserKey(UUID.randomUUID().toString());
        }
    }
}
